package cn.tedu.spring.jdbc;

import com.alibaba.druid.pool.DruidDataSource;
import org.junit.jupiter.api.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import java.sql.Connection;
import java.sql.SQLException;

/**
 * @author ruoLi
 */
public class TestJdbc {
    private static DruidDataSource dataSource;

    static {
        dataSource = new DruidDataSource();
        dataSource.setUrl("jdbc:mysql://localhost:3306/tedu?characterEncoding=utf8&useSSL=false&serverTimezone=Asia/Shanghai&rewriteBatchedStatements=true");
        dataSource.setUsername("root");
        dataSource.setPassword("root");
        dataSource.setMaxActive(30);
        dataSource.setInitialSize(5);
    }

    public Connection getConnection() throws SQLException {
        return dataSource.getConnection();
    }

    @Test
    public void demo01() {
        //原生druid连接数据库
        try {
            Connection connection = getConnection();
            if (connection != null) {
                System.out.println("数据库连接成功");
                return;
            }
            System.out.println("数据库连接失败");
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    @Test
    public void demo02() throws SQLException {
        ApplicationContext context = new ClassPathXmlApplicationContext("bean-jdbc.xml");
        dataSource = context.getBean("druidDataSource", DruidDataSource.class);
        Connection connection =  dataSource.getConnection();
        if (connection!=null){
            System.out.println("数据库连接成功！");
            return;
        }
        System.out.println("数据库连接失败！");
    }
}
